{% extends "base.html" %}

{% block content %}
<div class="page-title">
    <h3>在下方添加采购明细：</h3>
</div>
<div class="form-container">
    <form id="add-purchase-detail-form">
        <!-- Input fields for PurchaseDetail -->
        <label for="id">采购明细号：</label>
        <input type="number" id="id" name="id" class="input-field" required><br>
        <label for="purchase_id">采购清单号：</label>
        <input type="number" id="purchase_id" name="purchase_id" class="input-field" required><br>
        <label for="product_id">商品编号：</label>
        <input type="number" id="product_id" name="product_id" class="input-field" required><br>
        <label for="quantity">采购数量：</label>
        <input type="number" id="quantity" name="quantity" class="input-field" required><br>
        <label for="unit_price">商品单价：</label>
        <input type="number" id="unit_price" name="unit_price" class="input-field" required><br>
        <label for="total_price">商品总价：</label>
        <input type="number" id="total_price" name="total_price" class="input-field" required><br>
        <label for="remark">备注：</label>
        <textarea id="remark" name="remark" class="input-field"></textarea><br>
        <div class="button-container">
            <button type="submit" class="login-button">保存</button>
            <button type="reset" class="login-button" style="background-color: grey;">重置</button>
        </div>
    </form>
</div>

<script>
    document.getElementById('add-purchase-detail-form').addEventListener('submit', function(event) {
        event.preventDefault();

        const formData = new FormData(this);
        const data = Object.fromEntries(formData.entries());

        fetch(`/api/purchases/${data.purchase_id}/details`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        }).then(response => {
            if (response.ok) {
                alert('采购明细添加成功');
                this.reset();
            } else {
                response.json().then(data => {
                    if (response.status === 409) {
                        alert('添加采购明细失败: ' + data.error);  // Display specific error message
                    } else {
                        alert('添加采购明细失败: ' + data.error);  // General error handling
                    }
                });
            }
        }).catch(error => {
            console.error('Error:', error);
            alert('添加采购明细失败');
        });
    });

    document.querySelector('button[type="reset"]').addEventListener('click', function(event) {
        if (!confirm('是否确定重置已输入信息？')) {
            event.preventDefault();
        }
    });
</script>
{% endblock %}
